package com.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/helloworld")
public class HelloServlet extends HttpServlet {

    public HelloServlet() {
        System.out.println("HelloServlet对象创建了");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("HelloServlet初始化");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("HelloServlet被访问了");
    }

    @Override
    public void destroy() {
        System.out.println("HelloServlet销毁了");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求参数编码
        req.setCharacterEncoding("UTF-8");
        // 设置响应数据编码
        resp.setCharacterEncoding("UTF-8");
        // 获取请求参数
        String name = req.getParameter("name");
        System.out.println("name = " + name);
        String age = req.getParameter("age");
        System.out.println("age = " + age);
        //通过响应数据流，向浏览器发送数据
        resp.getWriter().write("你好！我叫：" + name + "，年龄是：" + age);
        // 实现重定向
        resp.sendRedirect("https://www.baidu.com?wd=" + name);
    }
}
